namespace Xmef.Serializer
{
    using System;
    using Xmef.Interfaces;
    using Xmef.Library;

    [Serializable]
    public abstract class XmlFileStreamSerializer<T> : XmlStreamSerializer<T>, IXmlFileStreamSerializer<T>, IXmlSerializer<T>, IExtensible<string>
    {
        private string _fileName;

        protected XmlFileStreamSerializer()
        {
        }

        public abstract bool Attach(string key);

        protected bool AttachFile(string key)
        {
            lock (((XmlFileStreamSerializer<T>)this))
            {
                if (this._fileName == null)
                {
                    this._fileName = key;
                    return true;
                }
                return false;
            }
        }

        protected abstract bool Deserialize(IXmlTypeFormatter formatter);
        
        public abstract bool Detach(string key);

        protected bool DetachFile(string key)
        {
            lock (((XmlFileStreamSerializer<T>)this))
            {
                if (this._fileName == key)
                {
                    this._fileName = null;
                    return true;
                }
                return false;
            }
        }

        protected abstract bool Serialize(T obj, IXmlTypeFormatter formatter);
        bool IXmlFileStreamSerializer<T>.Deserialize()
        {
            lock (((XmlFileStreamSerializer<T>) this))
            {
                return this.Deserialize(XmlTypeFormatter);
            }
        }

        bool IXmlFileStreamSerializer<T>.Deserialize(IXmlRuntimeFormatter formatter)
        {
            lock (((XmlFileStreamSerializer<T>) this))
            {
                try
                {
                    return this.Deserialize(formatter);
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrorSync(ex);
                }
                return false;
            }
        }

        bool IXmlFileStreamSerializer<T>.Serialize(T obj)
        {
            lock (((XmlFileStreamSerializer<T>) this))
            {
                return this.Serialize(obj, XmlTypeFormatter);
            }
        }

        bool IXmlFileStreamSerializer<T>.Serialize(T obj, IXmlRuntimeFormatter formatter)
        {
            lock (((XmlFileStreamSerializer<T>) this))
            {
                try
                {
                    return this.Serialize(obj, formatter);
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrorSync(ex);
                }
                return false;
            }
        }

        public string FileName
        {
            get
            {
                return this._fileName;
            }
        }
    }
}

